package com.xiaoye.qbdatahandle.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.xiaoye.qbdatahandle.domian.AjaxResult;
import com.xiaoye.qbdatahandle.domian.CollectionResult;
import com.xiaoye.qbdatahandle.service.CollectionResultService;
import com.xiaoye.qbdatahandle.service.TextAnalyzerService;
import com.xiaoye.qbdatahandle.util.MongoUtil;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 采集结果
 * @author: ChenYao
 */

@RestController
@RequestMapping("/collectionResult")
public class CollectionResultController {
    @Autowired
    CollectionResultService collectionResultService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    TextAnalyzerService textAnalyzerService;

    @GetMapping("/list")
    public AjaxResult list(@RequestParam int page,
                           @RequestParam int size, CollectionResult collectionResult) {
        page = MongoUtil.getModalPn(page);
        Criteria criteria = new Criteria();
        // 标题模糊查询
        if (StringUtils.isNotBlank(collectionResult.getTitle())) {
            criteria.and("title").regex(collectionResult.getTitle());
        }
        // 关键词模糊查询
        if (StringUtils.isNotBlank(collectionResult.getKeywords())) {
            criteria.and("keywords").regex(collectionResult.getKeywords());
        }
        if (StringUtils.isNotBlank(collectionResult.getTid())) {
            criteria.and("_tid").is(new ObjectId(collectionResult.getTid()));
        }
        Query query = Query.query(criteria);
        // 创建分页参数
        Pageable pageable = PageRequest.of(page, size);
        long count = mongoTemplate.count(query, CollectionResult.class);
        query.with(Sort.by(Sort.Order.desc("publish_time"))).skip((long) page * size).limit(size);
        List<CollectionResult> list = mongoTemplate.find(query.with(pageable), CollectionResult.class);
        IPage<CollectionResult> pages = MongoUtil.getModalIPage(page, size, count, list);
        return AjaxResult.success(pages);
    }

    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        CollectionResult collectionResult = mongoTemplate.findById(id, CollectionResult.class);
        if (collectionResult == null) {
            return AjaxResult.error("结果不存在");
        }
        return AjaxResult.success(collectionResult);
    }


    /**
     * @param id
     * @description: 获取词频
     * @author: ChenYao
     * @return: com.xiaoye.qbdatahandle.domian.AjaxResult
     * @ceateDate: 2025/2/21 下午4:30
     */

    @GetMapping("/getWordFrequency/{id}")
    public AjaxResult getWordFrequency(@PathVariable("id") String id) {
        // 或者 采集结果内容
        CollectionResult collectionResult = mongoTemplate.findById(id, CollectionResult.class);
        if (collectionResult == null) {
            return AjaxResult.error("结果不存在");
        }
        String text = collectionResult.getContent();
        if (StringUtils.isBlank(text)) {
            return AjaxResult.error("内容为空");
        }
        // 获取词频数据
        Map<String, Integer> wordFrequency = textAnalyzerService.analyzeText(text);
        return AjaxResult.success(wordFrequency);
    }

    @PostMapping
    public AjaxResult add(@RequestBody CollectionResult collectionResult) {
        collectionResult.setCreateTime(DateUtil.formatDate(new Date()));
        collectionResult.setUpdateTime(DateUtil.formatDate(new Date()));
        collectionResult.setIsHandle(false);
        mongoTemplate.insert(collectionResult);
        return AjaxResult.success();
    }

    @PutMapping()
    public AjaxResult edit(@RequestBody CollectionResult collectionResult) {
        // 更新文章
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(collectionResult.getId()));
        Update update = new Update();
        update.set("title", collectionResult.getTitle());
        String keywords = collectionResult.getKeywords();
        if (StringUtils.isNotBlank(keywords)) {
            update.set("keywords", keywords);
        }
        String content = collectionResult.getContent();
        if (StringUtils.isNotBlank(content)) {
            update.set("content", content);
        }
        String intro = collectionResult.getIntro();
        if (StringUtils.isNotBlank(intro)) {
            update.set("intro", intro);
        }
        String cover = collectionResult.getCover();
        if (StringUtils.isNotBlank(cover)) {
            update.set("cover", cover);
        }
        String publishTime = collectionResult.getPublishTime();
        if (publishTime != null) {
            update.set("publish_time", publishTime);
        }
        String source = collectionResult.getSource();
        if (StringUtils.isNotBlank(source)) {
            update.set("source", source);
        }
        update.set("update_time", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, CollectionResult.class);
        return AjaxResult.success(updateResult.getMatchedCount());
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") String id) {
        Criteria criteria = Criteria.where("id").is(id);
        DeleteResult deleteResult = mongoTemplate.remove(new Query(criteria), CollectionResult.class);
        return AjaxResult.success();
    }

    /**
     * @description: 处理采集结果
     * @author: ChenYao
     * @return: com.xiaoye.qbdatahandle.domian.AjaxResult
     * @ceateDate: 2025/2/20 下午6:38
     */


    @PostMapping("/handleResult")
    public AjaxResult handleResult() {
        collectionResultService.handleResult();
        return AjaxResult.success();
    }
}
